//
//  SelectCountryViewModel.swift
//  ImGuider X
//
//  Created by 陆涛 on 2018/9/28.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit

class SelectCountryViewModel: NSObject {

    var dataSource:[String:[Country]] = [:]
    var indexArray:[String] = []
    
    var loadFinished:((String?)-> Void)?
    
    func reloadData() {
        
        NetAPI.allcountry.request([Country].self, dealJson: "country") {
            
            [weak self] response, errmsg in
            guard let `self` = self else { return }
            
            if let array = response as? [Country] {
                
                self.dealData(array)
            } else {
                
                self.loadFinished?(errmsg)
            }
        }
    }
    
    private func dealData(_ data:[Country]) {
        
        DispatchQueue.global().async {

            [weak self] in
            guard let `self` = self else { return }
            
            for country in data {
                
                let initial = country.initial
                
                if var array = self.dataSource[initial] {
                    
                    array.append(country)
                    self.dataSource[initial] = array
                    continue
                }
                
                var array:[Country] = []
                array.append(country)
                self.indexArray.append(initial)
                self.dataSource[initial] = array
            }
            
            self.indexArray.sort()
            
            DispatchQueue.main.async {
                
                self.loadFinished?(nil)
            }
        }
    }
}
